<template>
	<view class="wrap">
		<u-navbar title="搜索设备" bgColor="#ffffff" safeAreaInsetTop :placeholder="true" leftIconColor="#000000"
			@leftClick="back" titleStyle="{fontSize: 16px;font-weight: bold;color: #000000;}">
		</u-navbar>
		<view class="breo-top">
			<view class="top-tabbar">搜索到{{arrList.length || 0}}个设备</view>
			<view class="top-img">
				<image class="imgs-tran" :class="refreshType ? 'tran-start' : 'tran-stop'" src="/static/ble/refresh.png"
					mode=""></image>
			</view>
		</view>
		<view v-if="arrList.length">
			<view class="breo-bottom" v-for="(item, index) in arrList" :key="index">
				<view class="equipment-list">
					<view class="list-img">
						<image :src="item.imgUrl" mode=""></image>
					</view>
					<view class="list-information">
						<view class="information-name">
							{{item.name}}
						</view>
						<view class="information-number">
							设备编号：{{item.name}}
						</view>
						<view class="connect-btn">
							<view class="list-btn" @tap="createBLEFun(item)">
								连接
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view v-else-if="!arrList.length && refreshType">
			<view class="noSearch">
				<u--image class="images" src="/static/img/search.png" width="484rpx" height="356rpx">
				</u--image>
				<view class="noSearchText">
					正在搜索...
				</view>
				<view class="fonts">
					<view class="tops">
						<u--image class="imagesIn" src="/static/img/exclamatoryImg.png" width="24rpx" height="24rpx">
						</u--image>
						<view class="topFont">
							请打开「姜小竹智能硬件」
						</view>
					</view>
					<view class="btm">
						并确保手机蓝牙处于打开状态
					</view>
				</view>
			</view>
		</view>
		<view v-else-if="!arrList.length && !refreshType">
			<view class="noSearch">
				<u--image class="images" src="/static/img/search.png" width="484rpx" height="356rpx">
				</u--image>
				<view class="noSearchText">
					未搜索到设备 请再次搜索
				</view>
				<view class="btns" @tap="startBluetoothDevicesDiscovery()">
					重新搜索
				</view>
				<view class="fonts">
					<view class="tops">
						<u--image class="imagesIn" src="/static/img/exclamatoryImg.png" width="24rpx" height="24rpx">
						</u--image>
						<view class="topFont">
							请打开「姜小竹智能硬件」
						</view>
					</view>
					<view class="btm">
						并确保手机蓝牙处于打开状态
					</view>
				</view>
			</view>
		</view>


		<u-popup :show="show" :round="20" mode="bottom" @close="close">
			<view class="popup-connect">
				<view class="popup-name">
					姜小竹A1艾灸盒
				</view>
				<image class="popup-img" src="/static/ble/connect.png" mode=""></image>
				<view class="popup-font">
					连接中...
				</view>
				<!-- <view class="popup-btn" @tap="onClose()">
					取消
				</view> -->
			</view>
		</u-popup>
		<u-popup :show="activationSuccessType" :round="20" mode="center" @close="close">
			<view class="activeationPopup">
				<view class="popup-name">
					{{details.name}}{{details.number}}
				</view>
				<view class="popup-font">
					首次激活成功
				</view>
				<image class="popup-img" src="/static/ble/connect.png" mode=""></image>
				<view class="popup-btn" @tap="onGotoManipulation()">
					开始艾灸
				</view>
				<view class="popupPs">
					注：激活后仅在有效期内可获得元气
				</view>
			</view>
		</u-popup>
		<example-popup ref="examplePopups"  @prompt="onPromptFun()"></example-popup>
	</view>
</template>

<script>
	import examplePopup from '@/pages/town/components/examplePopup.vue';
	import Bluetooth from '@/pages/town/common/Bluetooth.js';
	import {
		detailsr,
		massageActivation,
		massageRun
	} from '@/api/bluetooth.js'
	import {
		ab2hex
	} from '@/pages/town/common/filter.js';
	let bluetooth = new Bluetooth();
	export default {
		components: {
			examplePopup
		},
		data() {
			return {
				activationSuccessType: false,
				show: false,
				arrList: [],
				refreshType: false, //搜索是否完毕
				ids: '',
				macAddress: '', //mac地址
				details: {},
				messageCode: '', //硬件绑定code
				timeMessage: '', //元气产出定时器
			}
		},
		onReady() {
			setTimeout(() => {}, 2000)
		},
		onLoad(e) {
			if (e.id) {
				this.ids = e.id
			}
			bluetooth.openBluetoothAdapter().then(() => {
				this.startBluetoothDevicesDiscovery()
			})
		},
		computed: {},
		methods: {
			//用户点击单选按钮回调
			onPromptFun(id){
				switch(id){
					case 1:
						this.$refs.examplePopups.onClose();
						break;
					default:
						break;
				}
			},
			back() {
				if(this.show){
					this.$refs.examplePopups.onPrompt(true, '元气硬件', `设备正在连接中`, `请不要退出...`, 1, 'search')
				} else {
					uni.navigateBack()
				}
			},
			/**
			 * @param {Object} item 连接某个BLE蓝牙
			 */
			createBLEFun(item) {
				console.log('search', item)
				this.show = true
				let deviceId = item.deviceId
				this.onMassageActivation(item).then((res) => {
					bluetooth.createBLEConnection(deviceId).then(res => {
						this.connectionStatus = true
						this.connectedItem = item
						bluetooth.getBLEDeviceServices().then(service => {
							let i;
							if (uni.getSystemInfoSync().platform == 'android') {
								i = 2
								uni.setStorageSync('servicesId', service[i].uuid);
								console.log('uuid', service[i].uuid)
								bluetooth.getBLEDeviceCharacteristics(2).then(rest => {
									this.onResdBle();
								});
							} else {
								i = 0
								uni.setStorageSync('serviceId', service[i].uuid);
								bluetooth.getBLEDeviceCharacteristics().then(ints => {
									this.onResdBle();
								});
							}
							this.onclose()
						}).catch(err => {
							this.onclose()
						})
					}).catch(err => {
						this.onclose()
					})
				}).catch((err) => {
					console.log(456, err)
				})
			},
			//连接成功 跳转下一页
			onGotoManipulation() {
				if (this.messageCode == 200) {
					clearInterval(this.timeMessage)
				}
				uni.setStorageSync('connectData', {})
				uni.redirectTo({
					url: `./manipulation?id=${this.ids}`
				})
			},
			//首次链接进行绑定并进行加密
			async onMassageActivation(e) {
				try {
					let _this = this
					let data = {
						props_id: _this.ids,
						hardware_address: _this.onMacAddress(e)
					}
					console.log(123, data)
					let param = {
						data: _this.$rsa.rsaEncrypt(JSON.stringify(data)),
						timestamp: _this.$rsa.nowTime(),
						nonce: _this.$rsa.randomString(16)
					}
					var datas = await detailsr({
						hardware_id: _this.ids
					})
					var detailsrs = await massageActivation(
						Object.assign(param, {
							sign: _this.$rsa.onRsaSign(param)
						}))
					this.details = datas.data
					this.messageCode = detailsrs.code
					this.timeMessage = setInterval(() => {
						this.onMessageRun()
					}, 15000)
					return Promise.resolve(true);
				} catch (e) {
					console.log('err', e)
					this.messageCode = e.code
					if (e.code != 10043) {
						uni.showToast({
							title: '绑定失败，请重新绑定！',
							icon: 'none',
							duration: 3000
						})
						this.show = false
						return Promise.reject(false);
					}
				}
			},
			async onMessageRun() {
				let _this = this
				try {
					let data = {
						id: _this.ids
					}
					let param = {
						data: _this.$rsa.rsaEncrypt(JSON.stringify(data)),
						timestamp: _this.$rsa.nowTime(),
						nonce: _this.$rsa.randomString(16)
					}
					var datas = await massageRun(
						Object.assign(param, {
							sign: _this.$rsa.onRsaSign(param)
						})
					)
				} catch (err) {
					console.log('失败', err)
					clearInterval(_this.timeMessage)
				}
			},
			//开始启用各个命令，进行握手后进入页面
			async onResdBle() {
				let _this = this
				console.log('进入')
				bluetooth.notifyBLECharacteristicValue().then(infos => {
					bluetooth.stopBluetoothDevicesDiscovery() //停止蓝牙搜索
					_this.refreshType = false
					if (_this.messageCode == 10043) {
						_this.onGotoManipulation();
						this.show = false
					}
				}); //开始启用notify功能

			},
			//开始搜索蓝牙
			startBluetoothDevicesDiscovery(timeOut = 20000) {
				this.refreshType = true
				return new Promise((resolve, reject) => {
					setTimeout(() => {
						uni.startBluetoothDevicesDiscovery({
							success: res => {
								console.log('res' ,res)
								plus.bluetooth.onBluetoothDeviceFound((onts) => {
									for (let i = 0; i < onts.devices.length; i++) {
										if (onts.devices[i].name.indexOf("BREO_AJ") !=
											-1) {
											this.arrList.push({
												...onts.devices[i],
												imgUrl: '/static/ble/img_main_list.png'
											});
										}
									}
								})
							},
							fail: res => {
								bluetooth.showToast(`搜索设备失败` + JSON.stringify(err));
								bluetooth.stopBluetoothDevicesDiscovery()
								reject(err);
							}
						})
						setTimeout(() => {
							bluetooth.stopBluetoothDevicesDiscovery()
							this.refreshType = false
						}, timeOut)
					}, 300);
				})
			},
			onclose() {
				this.show = false
				if (this.messageCode == 200) {
					this.activationSuccessType = true;
				}
			},
			close() {

			},
			//获取MAC地址
			onMacAddress(e) {
				let i, iosMac = [],
					androidMac = [];
				if (uni.getSystemInfoSync().platform == 'android') {
					return e.deviceId
				} else {
					//IOS没有mac地址 要先把advertisData（buffer）转为数据字符串 截取从第六位后面的字符串就是MAC地址
					//因为直接打印advertisData是没有值，所以直接转就可以了 嘻嘻
					let data = this.ab2hex(e.advertisData).toString().substr(6)
					var result = "";
					for (let i = 0; i < data.length; i++) {
						result += data[i];
						if (i % 2 === 1) result += ':';
					}
					return result
				}
			},
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
		}
	}
</script>

<style lang="scss">
	.noSearch {
		text-align: center;

		.images {
			margin: 200rpx 0 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.noSearchText {
			font-size: 32rpx;
			margin-bottom: 144rpx;
			color: #ababab;
		}

		.btns {
			background: #5EB1FF;
			color: #FFFFFF;
			padding: 22rpx 0;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 100rpx;
			margin-bottom: 40rpx;
		}

		.fonts {
			font-size: 24rpx;
			color: #a5a5a5;

			.tops {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 12rpx;

				.topFont {
					margin-left: 8rpx;
				}
			}
		}
	}

	.activeationPopup {
		padding: 28rpx 88rpx 40rpx;
		text-align: center;

		.popup-name {
			font-size: 28rpx;
			color: #a3a3a3;
			margin-bottom: 16rpx;
		}

		.popup-font {
			color: #000000;
			font-size: 40rpx;
			font-weight: 700;
		}

		.popup-img {
			width: 218rpx;
			height: 256rpx;
			margin: 30rpx 0 46rpx;
		}

		.popup-btn {
			border-radius: 100px;
			color: #FFFFFF;
			padding: 14rpx 0;
			font-size: 32rpx;
			letter-spacing: 2rpx;
			background: #5EB2FF;
			margin-bottom: 24rpx;
		}

		.popupPs {
			font-size: 24rpx;
			color: #a3a3a3;
		}
	}

	.popup-connect {
		padding: 64rpx 66rpx;
		text-align: center;

		.popup-name {
			text-align: center;
			font-size: 64rpx;
			color: #5B616C;
		}

		.popup-img {
			margin: 80rpx 0 46rpx;
			width: 222rpx;
			height: 256rpx;
		}

		.popup-font {
			color: #00ACFF;
			font-size: 28rpx;
			font-weight: 400;
			color: #00ACFF;
			margin-bottom: 48rpx;
		}

		.popup-btn {
			background: #E9ECF2;
			border-radius: 16rpx;
			font-weight: 600;
			color: #5B616C;
			padding: 28rpx 0;
			font-size: 32rpx;
			letter-spacing: 2rpx;
		}
	}

	.wrap {
		padding: 40rpx 40rpx;
	}

	.breo-top {
		margin-bottom: 40rpx;
		display: flex;
		align-items: center;

		.top-tabbar {
			font-size: 28rpx;
			font-weight: 400;
			color: #181818;
		}

		.top-img {
			margin-left: 12rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.imgs-tran {
				width: 32rpx;
				height: 32rpx;
			}

			.tran-start {
				animation: whirling 2s infinite;
			}

			.tran-stop {
				animation-play-state: paused;
			}
		}
	}

	.breo-bottom {
		border-radius: 10rpx;
		background: #FFFFFF;
		padding: 32rpx 40rpx;
		box-shadow: 0rpx 12rpx 16rpx 0rpx rgba(0, 0, 0, 0.03);
		margin-bottom: 26rpx;

		.equipment-list {
			display: flex;

			.list-img {
				image {
					width: 148rpx;
					height: 148rpx;
				}
			}

			.list-information {
				margin-left: 40rpx;
				width: 100%;

				.information-name {
					margin: 8rpx 0 12rpx;
					font-size: 32rpx;
					font-weight: 500;
					color: #181818;
				}

				.information-number {
					font-size: 28rpx;
					color: #7B7B7B;
				}

				.connect-btn {
					display: flex;
					justify-content: flex-end;

					.list-btn {
						border-radius: 28rpx;
						border: 2rpx solid #01D2D3;
						color: #01D2D3;
						font-size: 28rpx;
						width: 136rpx;
						text-align: center;
						margin-top: 32rpx;
						padding: 8rpx 4rpx;
					}
				}

			}

		}
	}

	@keyframes whirling {
		0% {
			transform: rotate(0deg);
		}

		50% {
			transform: rotate(180deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>
